package dc.sockettest;

import sun.awt.windows.WPrinterJob;
import java.io.*;
import java.net.Socket;
import java.net.SocketException;

public class EchoClientsMultiThread {
    public static void main(String[] args) {
        //设置client的数量
        //可以设置成<core<waitingqueue+core<waitingqueue+core+max<来test
        int clientnums=3;

        for(int i=0;i<=clientnums;i++){
            clientThread clientTest=new clientThread();
            clientTest.start();
            //创建完一个client停一下看下结果
            try {
                Thread.currentThread().sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

class clientThread extends Thread{

    public void run(){
        String userInput = null;
        String echoMessage = null;
        BufferedReader stdIn = null;
        Socket socket = null;
        InputStream inStream = null;
        OutputStream outStream = null;
        BufferedReader in = null;
        PrintWriter out = null;

        try{
            stdIn = new BufferedReader(new InputStreamReader(System.in));

            //创建套接字
            socket = new Socket("127.0.0.1", 8189);
            System.out.println("Connected to Server");

            //建立连接
            inStream = socket.getInputStream();
            outStream = socket.getOutputStream();
            in = new BufferedReader(new InputStreamReader(inStream));
            out = new PrintWriter(outStream);

            //通信
            while((userInput=stdIn.readLine())!=null)
            {
                out.println(userInput);
                out.flush();
                echoMessage = in.readLine();
                System.out.println("to "+this.getName()+" Echo from server: " + echoMessage+"\n");
            }

        }catch (SocketException e){
            System.out.println("Error:\n"+e);
        }catch (IOException e){
            System.out.println("Error:\n"+e);
        }finally {
            try {
                //关闭IO和关闭socket
                if (out!=null)
                    out.close();
                if (in!=null)
                    in.close();
                if (outStream!=null)
                    outStream.close();
                if (inStream!=null)
                    inStream.close();
                if (stdIn!=null)
                    stdIn.close();
                if (socket!=null)
                    socket.close();
            }catch (Exception e){
                System.out.println("Error:"+e);
            }
        }
    }
}